<template>

    <div style="height: 100%;width: 100%;display: flex;justify-content: center">
        <div style="height: 75%;width: 65%;display: flex">
            <div  ref="chatContainer"  style="flex: 1;background-image: linear-gradient(to bottom, #fff1eb 0%, #fff1eb 65%);width: 100%;height: 100%;overflow-y: auto;position:relative;">

              <div v-for="item in message_arr_me" style="width: 100%;height: 150px;">
                <div v-if="item.userId" style="position: relative">
                  <img src="/imgs/chat/customer.svg" style="width: 68px;position: absolute;right: 30px">
                  <span style="color: #0a9eed;position: absolute;top: 70px;right: 50px">{{ user.username }}</span>
                  <div style="position: absolute;right: 130px;margin-top: 30px;background-color: #8bdaac;border-radius: 6px;padding: 15px">
                    <span style="color: #666666">{{item.message}}</span>
                  </div>
                </div>
                <div v-if="!item.userId" style="position: relative">
                  <img v-if="item.serId !== 0" src="/imgs/chat/ser.svg" style="width: 68px;position: absolute;left: 30px">
                  <img v-else src="/imgs/chat/machine.svg" style="width: 68px;position: absolute;left: 30px">
                  <span style="color: #0a9eed;position: absolute;top: 80px;left: 40px">{{ item.serName }}</span>
                  <div style="position: absolute;left: 130px;margin-top: 30px;background-color: #ace0f9;border-radius: 6px;padding: 15px">
                    <span style="color: #666666">{{item.message}}</span>
                  </div>
                </div>
              </div>

                <div style="height: 150px;width: 65%;position: fixed;z-index: 10;bottom: 25px" >
                    <el-input

                        v-model="message_to_send.message"
                        input-style="height:100px;"
                        maxlength="35"
                        style="width: 100%"
                        show-word-limit
                        placeholder="请输入"
                        type="textarea"
                        resize="none"
                    />
                    <el-button @click="send_message" type="success" style="border: none;cursor: pointer;position: absolute;right: 0;top: 100px">发送</el-button>

                </div>

            </div>
        </div>
    </div>
</template>

<script setup>
import {computed, nextTick, onMounted, ref} from 'vue';
import {ElInput, ElButton, ElContainer, ElMain, ElMessageBox, ElMessage} from 'element-plus';
import store from "@/store";

let socket = null
const user = ref(getUser())
const message_to_send = ref({userId: user.value.id,
    role: user.value.role,
    username: user.value.username,
    branchId: store.state.global_branch_Id,
    message: '',
    toWho: 0})

const message_arr_me = computed(()=>store.state.customer_message_arr);//计算属性
//const message_all = ref(new HashMap())

const chatContainer = ref(null);

const send_message = ()=>{

    if (!message_to_send.value.message.trim()) {
        ElMessage.warning('消息为空');
        return;
    }
    if (!socket || socket.readyState !== WebSocket.OPEN) {
        console.error('WebSocket is not open. Ready state:', socket ? socket.readyState : 'Socket is null');
        //ElMessage.error('WebSocket 连接未打开，请检查连接');
        //return;
        connect_to_websocket()

    }


    socket.send(JSON.stringify(message_to_send.value));
    //message_arr_me.value.push({userId:user.value.id,message:message_to_send.value.message})
    store.state.customer_message_arr.push({userId:user.value.id,message:message_to_send.value.message})
    message_to_send.value.message = '';
    scrollToBottom();
}
const connect_to_websocket = ()=>{

    if (socket && socket.readyState === WebSocket.OPEN) {
        console.log('WebSocket is already open.');
        ElMessage.info("WebSocket is already open.")
    }else {
        let userId = user.value.id
        let role = user.value.role
        let branchId = store.state.global_branch_Id
        let userRoleBranchId = userId+'_'+role+'_'+branchId

        socket = new WebSocket(`ws://127.0.0.1:8080/ws/message/${userRoleBranchId}`);//此处需要修改为后端服务器地址
        websocket_status()
    }
}
function websocket_status(){
    socket.onopen = () => {
        //ElMessage.success('连接打开,现在你可以发送消息了');

    };

    socket.onmessage = (event) => {
        /*{
	"message": "客服不在线哟~，请稍后联系我们",
	"serId": 0,
	"serName": "机器人"
}*/
        let message_source = JSON.parse(event.data);
        //message_arr_me.value.push(message_source);
        store.state.customer_message_arr.push(message_source)
        scrollToBottom();
    };

    socket.onclose = () => {
        //ElMessage.warning('连接关闭');
    };

    socket.onerror = (error) => {
        ElMessage.error('WebSocket error:');
    };
}
/*自动滚动到最底部*/
const scrollToBottom = async () => {
    await nextTick();
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
};

/*const change_input_ui = ()=>{
    document.getElementById("input_txt").style.height="150px"
}*/

onMounted(()=>{
    scrollToBottom()
    if(store.state.global_branch_Id===0){
        ElMessage.warning('未选择分店无法使用此功能')
    }else {
        connect_to_websocket()
    }
})



</script>

<style scoped>

</style>



